/**
 * Created by tongjunshui on 17/6/9.
 */
var express = require('express');
var router = express.Router();

var settings = require('../../settings');
var log = require('../../logger.js');
var md5 = require('md5');

var superagent = require('superagent');

var dbDao = require('../../models/dbBase.js');

var WXPay = require('weixin-pay');
var wxpay =  WXPay({
    appid: settings.appid,
    mch_id: settings.wxmch_id,
    partner_key: settings.wxmch_key, //微信商户平台API密钥
    //pfx: fs.readFileSync(__dirname+'/apiclient_cert.p12') //微信商户平台证书
});

//用于收取微信支付返回消息;/api/v1/pay/wx/notify
router.use('/wx/notify', wxpay.useWXCallback(function(msg, req, res, next){
    // 处理商户业务逻辑, 更新order表
    //console.log('--/wxpay/notify---');
    //console.log(msg);
    var sql = "update orders set orderStatus=? where id=?";
    var params = ['1', msg.out_trade_no];
    dbDao.querys(sql, params, function (err, result) {
        if(err){
            console.log('更新订单成功状态失败,订单号:',msg.out_trade_no);
        }else{
            console.log();
        }
    });
    //console.log('--/wxpay/notify end---');

    // res.success() 向微信返回处理成功信息，res.fail()返回失败信息。
    res.success();
}));

router.get('/wechat/:orderNo', function (req,res){
    var orderNo = req.params.orderNo || '';
    var wxopenid = req.query.wxopenid || '';

    console.log("这个页面点击后微信收款",orderNo,'wxid:',wxopenid);
    if((!orderNo)||(!wxopenid)){
        res.send({result:'error',message:'订单号或微信openid无效...'});
    }else{
        var sql = "select * from orders where id='" + orderNo + "'";
        dbDao.find( sql, function (err, result) {
            if (result.length > 0) {
                var sql2 = "select * from Gymnasium where id='" + result[0].gymId + "'";
                dbDao.find(sql2, function (err, result2) {
                    console.log('start---');
                    superagent.get('http://localhost:8804/webpay/')
                        .query('openid='+wxopenid)
                        .query('out_trade_no='+orderNo)
                        .query('total_fee=1') //result.payamount,测试时用1,superagent不能使用中文
                        .query('info='+'field_fee')
                        .query('detail='+'field_fee')
                        .end(function(err, result3){
                            console.log('end---');
                            if(err){
                                console.log("error:", err);
                                res.send({result:'error',message:''});
                            }else{
                                if(result3&&result3.body){
                                    console.log(result3.body);
                                    res.send({result:'success',data:result3.body});
                                }else{
                                    res.send({result:'error',message:''})
                                }
                            }
                        });
                });
            } else {
                log.logger.info('查不到订单err：' + err + 'orderNo=' + orderNo);
                res.send({result:'error',message:'订单号无效...'});
            }
        });
    }
});

router.get('/getWxSignature', function (req,res){

    var qUrl = req.headers.referer;
    console.log("---params:", qUrl);
    superagent.get(settings.gymPayApiBaseUrl+'/getSignature')
        .query('qurl='+qUrl)
        .end(function(err, result){
            if(err){
                console.log("error:", err);
                res.send({result:'error',message:''});
            }else{
                if(result&&result.body){
                    console.log(result.body);
                    res.send({result:'success',data:result.body});
                }else{
                    res.send({result:'error',message:'获取失败'})
                }
            }
        });

})
module.exports = router;